/* Susan(tm) Java Version
   by Thomas Lochmatter, Brig-Glis, Switzerland
   and Patrick Bizeau, Brig-Glis, Switzerland    */
   
package laWa;
import java.io.*;
import java.util.*;

// Manages the database
public class SusanDB {

  // ######################### INSTANCE VARIABLES
  java.util.List db;

  // ######################### CONSTRUCTOR
  public SusanDB() {
    loadDB();
  }

  // ######################### LOAD / SAVE DATABASE

  // Loads the database, reads all entries
  public void loadDB() {
    if (db!=null) {return;}
    db=new ArrayList();
    DataInputStream st2 = null;
    SusanDBEntry temp;
    String filename="laWa/db.dat";
    try {
      st2 = new DataInputStream(new FileInputStream(filename));
      while (true) {
        temp=new SusanDBEntry(st2);
        if (temp.field==null) {break;}
        db.add(temp);
      }
    } catch (IOException e) {
      System.out.println("An error occured while reading from the file "+filename+".");
    } finally {
      try {
        if (st2 != null) {st2.close();}
      } catch (IOException e) {
        System.out.println("An error occured while closing the file "+filename+".");
      }
    }
  }

  // Saves all entries back to the database file
  public void saveDB() {
    String filename="laWa/db.dat";
    System.out.println("Saving database ...");
    DataOutputStream st2 = null;
    try {
      st2 = new DataOutputStream(new FileOutputStream(filename));

      for (Iterator it = db.iterator(); it.hasNext(); ) {
        ((SusanDBEntry)it.next()).saveEntry(st2);
      }
    } catch (IOException e) {
      System.out.println("An error occured while writing to the file "+filename+". The database has not been saved.");
    } finally {
      try {
        if (st2 != null) {st2.close();}
      } catch (IOException e) {
        System.out.println("An error occured while closing the file "+filename+". The database may not be saved correctly.");
      }
    }
  }
}

// ######################### END OF FILE
